package com.example.cursor_service.impl;

import com.example.cursor_service.AttributePolicyService;
import com.example.cursor_orm.model.AttributePolicy;
import com.example.cursor_orm.dao.AttributePolicyDAO;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.ArrayList;

@Service
public class AttributePolicyServiceImpl implements AttributePolicyService {
    private final AttributePolicyDAO policyDAO;
    
    public AttributePolicyServiceImpl(AttributePolicyDAO policyDAO) {
        this.policyDAO = policyDAO;
    }
    
    @Override
    public AttributePolicy createPolicy(AttributePolicy policy) {
        try {
            policyDAO.insert(policy);
            return policy;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public AttributePolicy getPolicyById(Integer id) {
        try {
            return policyDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public AttributePolicy updatePolicy(Integer id, AttributePolicy policy) {
        try {
            policy.setId(id);
            policyDAO.update(policy);
            return policyDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public boolean deletePolicy(Integer id) {
        try {
            return policyDAO.deleteById(id) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<AttributePolicy> getPolicyList(int page, int size) {
        try {
            // 简单分页实现，实际可用SQL limit优化
            List<AttributePolicy> all = policyDAO.findAll();
            int from = Math.max(0, (page - 1) * size);
            int to = Math.min(all.size(), from + size);
            return all.subList(from, to);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<AttributePolicy> getPoliciesByRoleId(Integer roleId) {
        try {
            return policyDAO.findByRoleId(roleId);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<AttributePolicy> getPoliciesByPermissionId(Integer permissionId) {
        try {
            return policyDAO.findByPermissionId(permissionId);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<AttributePolicy> getPoliciesByAttribute(String key, String value) {
        try {
            return policyDAO.findByAttributeKeyAndValue(key, value);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
} 